# This file is part of the Net::Tube module.
#
# Net::Tube is Free Software; you can use, redistribute it and/or
# modify it under the terms of either:
#
# a) the GNU General Public License as published by the Free Software
#    Foundation, either version 2, or (at your opinion) any later
#    version, or
#
# b) the "Artistic License" which comes with Perl.
#
package Net::Tube::Filter::Sort::Date;

use Net::Tube::Filter::Sort;
our @ISA = qw(Net::Tube::Filter::Sort);

sub compare {
    my $self      = shift;
    my $nodeA     = shift;
    my $nodeB     = shift;
    my $direction = shift;

    my ( $ta, $tb );
    if ( defined $nodeA ) {
        $ta = $nodeA->textContent;
    }
    if ( defined $ta && length $ta ) {
        $ta = $self->convert_time($ta);
    }
    else {
        $ta = "";
    }
    if ( defined $nodeB ) {
        $tb = $nodeB->textContent;
    }
    if ( defined $tb && length $tb ) {
        $tb = $self->convert_time($tb);
    }
    else {
        $tb = "";
    }

    my $retval = ($ta cmp $tb);
    if ( $direction == Net::Tube::Filter::Sort::DESCENDING() ) {
        $retval *= -1;
    }
    return $retval;
}

sub convert_time {
    my $self = shift;
    my $tstr = shift;

    #  invalid date, which is always bigger than a date
    my $retval = "XXXXXXXXXXXXXXXXXXXXXXXXX";

    if ( defined $tstr && length $tstr ) {
        $tstr =~ s/^\s+|\s+$//g;
        my @date;
        if ( $tstr =~ /^\w{3}, (\d\d) (\w{3}) (\d{4}) (\d\d):(\d\d):(\d\d)/ ) {
            @date = ( $3, $2, $1, $4, $5, $6 );
            my %names = (
                jan   => '01',
                feb   => '02',
                mar   => '03',
                apr   => '04',
                may   => '05',
                jun   => '06',
                jul   => '07',
                aug   => '08',
                sep   => '09',
                'oct' => '10',
                nov   => '11',
                dec   => '12'
            );
            $date[1] = $names{ lc($date[1]) };
        }
        elsif ( $tstr =~ /^(\d{4})-(\d\d)-(\d\d)[Tt\s](\d\d):(\d\d):(\d\d)/ ) {
            @date = ( $1, $2, $3, $4, $5, $6 );
        }

        if ( scalar @date ) {
            $retval = sprintf '%04d-%02d-%02d %02d:%02d:%02d', @date;
        }
    }

    # warn $retval;
    return $retval;
}

1;
